<?php
namespace catchAdmin\externalGoods\model;

use catchAdmin\externalGoods\model\search\NotifySearch;
use catcher\base\CatchModel;
use think\Exception;
use think\facade\Db;

class NewNotify extends CatchModel
{
    //use NotifySearch;

    protected $name = 'db_syst_sync_new_notify';

    private $tableName = 'db_syst_sync_new_notify';// 私有属性，用于保存原来表名
    protected $tableCount = 12;//分表数量


//-- 创建 12 个表，表结构复制于 db_syst_sync_new_notify_1 表
//
//-- 创建表 db_syst_sync_new_notify_0
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_0 LIKE db_syst_sync_new_notify_1;
//
//-- 创建表 db_syst_sync_new_notify_1
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_1 LIKE db_syst_sync_new_notify_1;
//
//-- 创建表 db_syst_sync_new_notify_2
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_2 LIKE db_syst_sync_new_notify_1;
//
//-- 创建表 db_syst_sync_new_notify_3
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_3 LIKE db_syst_sync_new_notify_1;
//
//-- 创建表 db_syst_sync_new_notify_4
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_4 LIKE db_syst_sync_new_notify_1;
//
//-- 创建表 db_syst_sync_new_notify_5
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_5 LIKE db_syst_sync_new_notify_1;
//
//-- 创建表 db_syst_sync_new_notify_6
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_6 LIKE db_syst_sync_new_notify_1;
//
//-- 创建表 db_syst_sync_new_notify_7
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_7 LIKE db_syst_sync_new_notify_1;
//
//-- 创建表 db_syst_sync_new_notify_8
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_8 LIKE db_syst_sync_new_notify_1;
//
//-- 创建表 db_syst_sync_new_notify_9
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_9 LIKE db_syst_sync_new_notify_1;
//
//-- 创建表 db_syst_sync_new_notify_10
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_10 LIKE db_syst_sync_new_notify_1;
//
//-- 创建表 db_syst_sync_new_notify_11
//CREATE TABLE IF NOT EXISTS db_syst_sync_new_notify_11 LIKE db_syst_sync_new_notify_1;


    protected $defaultSoftDelete = null;
    protected $field = [
        'id',
        'type',
        'type_name',
        'status',
        'notify_data',
        'remark',
        'sign',
        'supplier_id',
        'created_at',
        'updated_at',
        'deleted_at',
        'tenant_id',
        'creator_id'
    ];

//    // 根据自增ID获取对应的分表名
//    public function getTableNameByUserId($userId)
//    {
//        $tableIndex = floor($userId / 10000); // 假设每个分表存放的ID段为1万个
//        return $this->name . '_' . $tableIndex;
//    }

    // 根据用户ID获取对应的分表名
    public function getTableName($userId)
    {
        $suffix = $userId % $this->tableCount; // 假设分5个表
        return $this->tableName . '_' . $suffix;
    }

    // 动态设置数据表名
    public function setTableName($userId)
    {
        $this->name = $this->getTableName($userId);
        return $this;
    }

//       添加用户并获取自增ID
//    public function addRecordAndReturnId($data)
//    {
//        // 插入到临时表中
//        $tempTableName = $this->name . '_temp';
//        Db::table($tempTableName)->insert($data);
//
//        // 获取自增ID
//        $lastInsertId = Db::query('SELECT LAST_INSERT_ID() AS id')[0]['id'];
//
//        // 根据自增ID选择分表
//        $tableName = $this->getTableNameById($lastInsertId);
//
//        // 将数据从临时表迁移到正确的分表中
//        Db::execute("INSERT INTO {$tableName} SELECT * FROM {$tempTableName}");
//
//        // 删除临时表
//        Db::execute("DROP TABLE {$tempTableName}");
//
//        return $lastInsertId;
//    }

    // 添加
    public function addRecord($data)
    {
        unset($data['id']);
        $tempTableName = $this->tableName . '_temp';
        Db::table($tempTableName)->insert($data);
        $lastInsertId = Db::table($tempTableName)->getLastInsID();
        Db::table($tempTableName)->where('id',$lastInsertId)->delete(true);
        //$tableName = $this->getTableName($lastInsertId);
        $this->setTableName($lastInsertId);
        $data['id'] = $lastInsertId;
        $lastInsertId =  $this->save($data);
        return $lastInsertId;
    }

    // 根据用户ID查询用户信息
    public function getRecordById($userId)
    {
        $this->setTableName($userId);
        return $this->where('id', $userId)->find();
    }

//    // 更新用户信息
//    public function updateUser($userId, $data)
//    {
//        $this->setTableName($userId);
//        return $this->where('id', $userId)->update($data);
//    }
//
//    // 删除用户
//    public function deleteRecord($id)
//    {
//        $this->setTableName($id);
//        return $this->where('id', $id)->delete();
//    }

    // 分页查询列表
    public function getRecordByPage($conditions=[], $page = 1, $limit = 10)
    {
        $whereClause = $this->generateWhereClause($conditions);

        $subQuery = [];
        for ($i = 0; $i < $this->tableCount; $i++) {
            $tableName = $this->tableName . '_' . $i;
            $subQuery[] = "(SELECT *, {$i} as shard FROM {$tableName} {$whereClause})";
        }
        $sql = implode(' UNION ALL ', $subQuery);
        $sql = "SELECT * FROM ({$sql}) tmp  ORDER BY id desc LIMIT " . (($page - 1) * $limit) . ", " . $limit;
        $data =  Db::query($sql);

        $count = $this->getTotalRowCount($conditions);

        // 调用数据处理函数对数据进行处理
        $data = $this->processFields($data);

        return ['count'=>$count, 'data'=>$data, 'sql'=>$sql];
    }

    // 处理查询结果
    public function processFields($data)
    {
        foreach ($data as &$item) {
            // 判断是否存在 created_at 字段
            if (isset($item['created_at'])) {
                $item['created_at'] = date('Y-m-d H:i:s', $item['created_at']);
            }

            if (isset($item['notify_data'])) {
                $item['notify_data'] = json_decode($item['notify_data'],true);
            }


            // 还可以添加其他字段的处理逻辑
        }
        return $data;
    }

    private function generateWhereClause($conditions)
    {
        if (empty($conditions)) {
            return '';
        }

        $whereClauses = [];
        foreach ($conditions as $key => $value) {
            // 处理比较操作符
            if (is_array($value)) {
                $operator = $value[0];
                $operand = $value[1];
                $whereClauses[] = "{$key} {$operator} '" . $operand . "'";
            } else {
                $whereClauses[] = "{$key} = '" . $value . "'";
            }        }
        return 'WHERE ' . implode(' AND ', $whereClauses);
    }

    public function getByTypeName($typeName)
    {
        $subQuery = [];
        for ($i = 0; $i < $this->tableCount; $i++) {
            $tableName = $this->tableName . '_' . $i;
            $subQuery[] = "(SELECT *, {$i} as shard FROM {$tableName} WHERE type_name = '" . $typeName . "')";
        }
        $sql = implode(' UNION ALL ', $subQuery);
        $sql = "SELECT * FROM ({$sql}) tmp";

        //dd($sql);

        return Db::query($sql);
    }

    public function getTotalRowCount($conditions=[])
    {
        $whereClause = $this->generateWhereClause($conditions);

        $subQuery = [];
        for ($i = 0; $i < $this->tableCount; $i++) {
            $tableName = $this->tableName . '_' . $i;
            $subQuery[] = "(SELECT COUNT(id) as count FROM {$tableName} {$whereClause})";
        }
        $sql = implode(' UNION ALL ', $subQuery);
        $sql = "SELECT SUM(count) as total_count FROM ({$sql}) tmp";

        $result = Db::query($sql);
        return (int) $result[0]['total_count'];
    }
}
